using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using Microsoft.SharePoint.Utilities;
using stsdev;

namespace ThemeSolutionProvider
{
  public class ThemeSolutionProvider : ISolutionProvider
  {
    public string Title
    {
      get { return "Theme Solution Generator (C# Assembly)"; }
    }

    public bool LaunchSolutionOnComplete
    {
      get { return false; }
    }

    public void InitializeSolution()
    {
      SolutionBuilder.AssemblyDeployment = true;
      SolutionBuilder.SafeControlSettings = false;
      SolutionBuilder.DeploymentTarget = AssemblyDeploymentTarget.GlobalAssemblyCache;
      SolutionBuilder.CasPermissions = false;
    }

    public void AddSolutionItems()
    {
        ThemeDetailsForm tdf = new ThemeDetailsForm();
        if (tdf.ShowDialog() != DialogResult.OK)
            return;
        // TODO: Can we do better than doing nothing?

        string newThemeID = tdf.ThemeID;
        string newThemeName = tdf.ThemeName;

        // Add FeatureThemesJob.cs to the project namespace
        ThemeResourceBuilder.CreateFeatureThemesJob(SolutionBuilder.SolutionName);

        // Add SPTHEMES.xml to the project
        ThemeResourceBuilder.CreateSPThemesXml(newThemeID, newThemeName, tdf.ThemeDescription, tdf.ThemeThumbnail, tdf.ThemePreview);

        Globals.FeatureActivatedCode.Append("FeatureThemesJob.InstallThemes(properties.Definition);");
        Globals.FeatureDeactivatingCode.Append("FeatureThemesJob.DeleteThemes(properties.Definition);");

        // TODO: Suggest FeatureBuilder.AddProperty(key, value)
        // FeatureBuilder.AddProperty("Solutionizing:ThemesFile", "SPTHEMES.XML");
        FeatureBuilder.Create("Theme: " + newThemeName, FeatureScopeEnum.Farm, true);

        // In the meantime, this should be the only property
        string featureXmlFilePath = string.Format(@"{0}\{1}\feature.xml", Globals.FeaturesFolder, SolutionBuilder.SolutionName);
        string contents = null;
        using (StreamReader reader = new StreamReader(featureXmlFilePath))
        {
            contents = reader.ReadToEnd();
        }

        contents = contents.Insert(contents.LastIndexOf("</Feature>"), Properties.Resources.FeatureProperties);

        using (StreamWriter writer = new StreamWriter(featureXmlFilePath))
        {
            writer.Write(contents);
        }

        // Create TEMPLATE\THEMES Folder
        if (!Directory.Exists(Globals.ThemesFolder))
        {
            Directory.CreateDirectory(Globals.ThemesFolder);
        }
        string newThemeFolder = Path.Combine(Globals.ThemesFolder, newThemeID);
        if (!Directory.Exists(newThemeFolder))
        {
            Directory.CreateDirectory(newThemeFolder);
        }
        ProjectFileBuilder.AddFolder(newThemeFolder);

        DirectoryInfo oldThemeDir = new DirectoryInfo(tdf.ThemeToCopy);
        string oldThemeDirName = oldThemeDir.Name;

        FileInfo[] files = oldThemeDir.GetFiles();
        foreach (FileInfo file in files)
        {
            string fileNameToAdd = file.Name;
            if (fileNameToAdd.Equals(oldThemeDirName + ".INF", StringComparison.InvariantCultureIgnoreCase))
            {
                fileNameToAdd = newThemeID + ".INF";
                using (StreamReader reader = file.OpenText())
                {
                    using (StreamWriter writer = new StreamWriter(Path.Combine(newThemeFolder, fileNameToAdd)))
                    {
                        string infContents = reader.ReadToEnd();
                        infContents = Regex.Replace(infContents, oldThemeDirName, newThemeID, RegexOptions.IgnoreCase);
                        writer.Write(infContents);
                    }
                }
            }
            else if (fileNameToAdd.Equals("theme.css", StringComparison.InvariantCultureIgnoreCase) && tdf.ConvertToCssImport)
            {
                string importPath = @"STYLES\" + newThemeID;
                string destination = Path.Combine(Globals.LayoutsFolder, importPath);
                if (!Directory.Exists(destination))
                    Directory.CreateDirectory(destination);
                destination = Path.Combine(destination, "theme.css");
                file.CopyTo(destination);
                ProjectFileBuilder.AddSourceFile(destination, SourceFileTypeEnum.Content);

                // Create theme.css from @import template
                ThemeResourceBuilder.CreateImportThemeCss(newThemeFolder, importPath.Replace('\\', '/'));
            }
            else
            {
                file.CopyTo(Path.Combine(newThemeFolder, fileNameToAdd));
            }
            ProjectFileBuilder.AddSourceFile(Path.Combine(newThemeFolder, fileNameToAdd), SourceFileTypeEnum.None);
        }

    }
  }
}
